package com.swufe.scoresforapp.adapter;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.Image;
import android.os.Handler;
import android.os.Message;
import android.support.v7.view.menu.MenuView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mcxtzhang.swipemenulib.SwipeMenuLayout;
import com.swufe.scoresforapp.CollectionActivity;
import com.swufe.scoresforapp.DrawerLayoutActivity;
import com.swufe.scoresforapp.GetChange;
import com.swufe.scoresforapp.GlideImageLoader;
import com.swufe.scoresforapp.R;
import com.swufe.scoresforapp.ScrollingSchoolActivity;
import com.swufe.scoresforapp.Yonghu.Dataimport;
import com.swufe.scoresforapp.Yonghu.Dataoutput;
import com.swufe.scoresforapp.bean.SchoolBean;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ASUS on 2018/7/8.
 */

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.AuthorViewHolder> {

    private Context mContext;
    private LayoutInflater mInflater;
    private List<SchoolBean> mSchools;
    private String fragment;
    private Handler handler;
    private onItemClickListener monItemClickListener;
    private String yonghu;
    private String rate;
    private String low;//当前学校或专业最低录取排名
    private String suggestion;
    private ImageView imageView;

    public RecyclerAdapter(Context context, List<SchoolBean> mSchools,String fragment) {
        mContext = context;
        mInflater = LayoutInflater.from(context);
        SharedPreferences preferences = mContext.getSharedPreferences("Data", Context.MODE_PRIVATE);
        yonghu = preferences.getString("Name","");
        this.mSchools = mSchools;
        this.fragment = fragment;
    }

    @Override
    public AuthorViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        final AuthorViewHolder viewHolder = new AuthorViewHolder(mInflater.inflate(R.layout.item_school, parent, false));

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(final AuthorViewHolder holder, final int position) {
        //这句话关掉IOS阻塞式交互效果 并依次打开左滑右滑
        ((SwipeMenuLayout)holder.itemView).setIos(false);//.setLeftSwipe(position % 2 == 0 ? true : false);
        GlideImageLoader loader = new GlideImageLoader();
        loader.displayImage(mContext,mSchools.get(position).photosource,holder.mimage);
        imageView = holder.mimage;
        holder.School.setVisibility(View.INVISIBLE);
        holder.low.setVisibility(View.INVISIBLE);
        holder.yonhu = mSchools.get(position).Yonghu;
        //Log.i("sql",holder.yonhu);
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if(msg.what == 7){
                    String rs = (String) msg.obj;
                    if(rs == null||rs.equals(""));
                    else if(rs.equals("删除成功"))mOnSwipeListener.onDel(holder.getAdapterPosition());
                    else if(rs.equals("删除失败"))Toast.makeText(mContext, "删除失败", Toast.LENGTH_SHORT).show();

                }else if(msg.what == 18){
                    List<String> m = (ArrayList<String>)msg.obj;

                    if(m!=null){
                        holder.School.setVisibility(View.VISIBLE);
                        holder.low.setVisibility(View.VISIBLE);
                        holder.School.setText(m.get(0));
                        holder.low.setText("录取概率："+m.get(1));
                    }
                    else{
                        holder.School.setVisibility(View.VISIBLE);
                        holder.School.setText("当前数据无法判断");
                    }

                }else  if(msg.what==17){
                    List<String> m = (ArrayList<String>)msg.obj;
                    if(m!=null&&!m.get(0).equals("")){
                        holder.School.setVisibility(View.VISIBLE);
                        holder.low.setVisibility(View.VISIBLE);
                        holder.School.setText(m.get(0));
                        holder.low.setText("录取概率："+m.get(1));
                    }
                    else{
                        holder.School.setVisibility(View.VISIBLE);
                        holder.School.setText("当前数据无法判断");
                    }
                }
                super.handleMessage(msg);
            }
        };
        if(fragment.equals("学校")) {

            holder.mNickNameView.setText(mSchools.get(position).Schoolname );
            holder.mRate.setText("点击查看详情");
            final Dataimport in = new Dataimport();
            new Thread(
                    new Runnable() {
                        @Override
                        synchronized public void run(){

                            // String school,String year,String major,String studentsource,String studenttype
                            String studenttype = in.getType(yonghu);
                            String studentfrom = in.getArea(yonghu);
                            low = in.getSchGuessLowOrder(mSchools.get(position).Schoolname,
                                    studentfrom,studenttype);
                            //String
                            String top = in.getTop(yonghu);
                            //Log.i("Sqltop",top);
                            String last = in.getLow(yonghu);
                            //Log.i("Sqllast",top);
                            String me = in.getOrder(yonghu);
                            //Log.i("Sqlme",top);
                            // Log.i("Sqllow",""+low);
                            Message msg = handler.obtainMessage(17);
                            if(!low.equals("无当年数据")&&!top.equals("")&&!last.equals("")&&!me.equals(""))
                                msg.obj = new GetChange().getChance(Integer.parseInt(low.trim()),Integer.parseInt(me.trim()),Integer.parseInt(last),Integer.parseInt(top));
                            handler.sendMessage(msg);

                        }
                    }
            ).start();
        }else if(fragment.equals("专业")){
            new Thread(
                new Runnable() {
                    @Override
                    synchronized public void run() {
                        Dataimport in = new Dataimport();
                        // String school,String year,String major,String studentsource,String studenttype
                        low = in.getGuessLowOrder(mSchools.get(position).Schoolname,
                                mSchools.get(position).major,mSchools.get(position).studentfrom,mSchools.get(position).studenttype);
                        //String
                        String top = in.getTop(yonghu);
                        //Log.i("Sqltop",top);
                        String last = in.getLow(yonghu);
                        //Log.i("Sqllast",top);
                        String me = in.getOrder(yonghu);
                        //Log.i("Sqlme",top);
                        // Log.i("Sqllow",""+low);
                        Message msg = handler.obtainMessage(18);
                        if(!low.equals("无当年数据")&&!top.equals("")&&!last.equals("")&&!me.equals(""))
                            msg.obj = new GetChange().getChance(Integer.parseInt(low.trim()),Integer.parseInt(me.trim()),Integer.parseInt(last),Integer.parseInt(top));
                        handler.sendMessage(msg);

                    }
                }
        ).start();
            holder.mNickNameView.setText(mSchools.get(position).major);
            holder.mRate.setText(mSchools.get(position).Schoolname);
            holder.low.setVisibility(View.INVISIBLE);
            holder.low.setText("录取最低: "+mSchools.get(position).low);
        }else if(fragment.equals("对比")){
            holder.mNickNameView.setText("1. "+mSchools.get(position).school1);
            holder.mNickNameView.setTextSize(16);
            holder.mRate.setText("2. "+mSchools.get(position).school2);
            holder.School.setVisibility(View.VISIBLE);
            holder.School.setText("3. "+mSchools.get(position).school3);
            holder.low.setVisibility(View.VISIBLE);
            holder.low.setText("4. "+mSchools.get(position).school4);
            holder.mimage.setVisibility(View.INVISIBLE);
        }else if(fragment .equals("主学校")){
            holder.mNickNameView.setText(mSchools.get(position).Schoolname );
            holder.mRate.setText("点击查看详情");
            new Thread(
                    new Runnable() {
                        @Override
                        synchronized public void run() {
                            Dataimport in = new Dataimport();
                            // String school,String year,String major,String studentsource,String studenttype
                            String studenttype = in.getType(yonghu);
                            String studentfrom = in.getArea(yonghu);
                            low = in.getSchGuessLowOrder(mSchools.get(position).Schoolname,
                                   studentfrom,studenttype);
                            //String
                            String top = in.getTop(yonghu);
                            //Log.i("Sqltop",top);
                            String last = in.getLow(yonghu);
                            //Log.i("Sqllast",top);
                            String me = in.getOrder(yonghu);
                            //Log.i("Sqlme",top);
                            // Log.i("Sqllow",""+low);
                            Message msg = handler.obtainMessage(17);
                            if(!low.equals("无当年数据")&&!top.equals("")&&!last.equals("")&&!me.equals(""))
                                msg.obj = new GetChange().getChance(Integer.parseInt(low.trim()),Integer.parseInt(me.trim()),Integer.parseInt(last),Integer.parseInt(top));
                            handler.sendMessage(msg);

                        }
                    }
            ).start();
        }else if(fragment.equals("主专业")){
            holder.mNickNameView.setText(mSchools.get(position).major);
            holder.mRate.setText(mSchools.get(position).Schoolname);
            new Thread(
                    new Runnable() {
                        @Override
                        synchronized  public void run() {
                            Dataimport in = new Dataimport();
                            // String school,String year,String major,String studentsource,String studenttype
                            low = in.getGuessLowOrder(mSchools.get(position).Schoolname,
                                    mSchools.get(position).major,mSchools.get(position).studentfrom,mSchools.get(position).studenttype);
                            //String
                            String top = in.getTop(yonghu);
                            //Log.i("Sqltop",top);
                            String last = in.getLow(yonghu);
                            //Log.i("Sqllast",top);
                            String me = in.getOrder(yonghu);
                            //Log.i("Sqlme",top);
                           // Log.i("Sqllow",""+low);
                            Message msg = handler.obtainMessage(18);
                            if(!low.equals("无当年数据")&&!top.equals("")&&!last.equals("")&&!me.equals(""))
                                msg.obj = new GetChange().getChance(Integer.parseInt(low.trim()),Integer.parseInt(me.trim()),Integer.parseInt(last),Integer.parseInt(top));
                            handler.sendMessage(msg);
                        }
                    }
            ).start();
        }
        //holder.


        //删除
        if(fragment.equals("主学校")||fragment.equals("主专业")){
            holder.mbtnDelete.setVisibility(View.INVISIBLE);
            holder.mbtnTop.setVisibility(View.INVISIBLE);
        }
            holder.mbtnDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null != mOnSwipeListener) {
                        //如果删除时，不使用mAdapter.notifyItemRemoved(pos)，则删除没有动画效果，
                        //且如果想让侧滑菜单同时关闭，需要同时调用 ((CstSwipeDelMenu) holder.itemView).quickClose();
                        //((CstSwipeDelMenu) holder.itemView).quickClose();

                        final String name = holder.mNickNameView.getText().toString();
                        final String rate = holder.mRate.getText().toString();
                        final String  school3 = holder.School.getText().toString();
                        final String  school4 = holder.low.getText().toString();

                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Dataoutput out = new Dataoutput();
                                Message msg = handler.obtainMessage(7);
                                Log.i("sql",fragment);
                                if(fragment.equals("学校")) msg.obj = out.deletShoucang(name,yonghu);
                                else if(fragment.equals("专业"))msg.obj = out.deletMajorShoucang(rate,name,yonghu);
                                else if(fragment.equals("对比"))msg.obj = out.deletCompareShoucang(yonghu,name,rate,school3,school4);
                                handler.sendMessage(msg);
                            }
                        }).start();

                    }

                }
            });

            //置顶：
            holder.mbtnTop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null!=mOnSwipeListener){
                        mOnSwipeListener.onTop(holder.getAdapterPosition());
                        //,, SharedPreferences preferences = ;
                    }

                }
            });

            holder.mbtnAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (null!=mOnSwipeListener) {
                        int position = holder.getAdapterPosition();
                        mOnSwipeListener.onAdd(position, imageView);
                    }
                }
            });



        //注意事项，设置item点击，不能对整个holder.itemView设置咯，只能对第一个子View，即原来的content设置，这算是局限性吧。
        (holder.mContent).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int pos = holder.getLayoutPosition();
                monItemClickListener.onItemClick(-55, holder.itemView, pos);
                Log.d("TAG", "onClick() called with: v = [" + v + "]");
            }
        });
        //验证长按
        holder.mContent.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                int pos = holder.getLayoutPosition();
                Toast.makeText(mContext, "longclig", Toast.LENGTH_SHORT).show();
                monItemClickListener.onItemLongClick(-55, holder.itemView, pos);
                Log.d("TAG", "onLongClick() called with: v = [" + v + "]");
                return false;
            }
        });
    }

    @Override
    public int getItemCount() {
        return null != mSchools ? mSchools.size() : 0;
    }
    /**
     * tag：区分点击的是什么
     * position:位置
     */
    public static interface onItemClickListener{
        void onItemClick(int tag, View view, int position);
        void onItemLongClick(int tag, View view, int position);
    }

    /**
     * 声明给外界的方法
     */
    public void setOnItemClickListener(onItemClickListener listener){
        this.monItemClickListener = listener;
    }


    /**
     * 和Activity通信的接口
     */
    public interface onSwipeListener {
        void onDel(int pos);

        void onTop(int pos);

        void onAdd(int pos, ImageView v);
    }

    private onSwipeListener mOnSwipeListener;

    public onSwipeListener getOnDelListener() {
        return mOnSwipeListener;
    }

    public void setOnDelListener(onSwipeListener mOnDelListener) {
        this.mOnSwipeListener = mOnDelListener;
    }

 /*   public void addData(int position) {
//      在list中添加数据，并通知条目加入一条
        mSchools.add(position, "我是商品" + position);
        //添加动画
        notifyItemInserted(position);
    }*/


    class AuthorViewHolder extends RecyclerView.ViewHolder {

        LinearLayout mContent;
        TextView mNickNameView,mRate,School,low;
        Button mbtnTop;
        Button mbtnDelete;
        Button mbtnAdd;
        ImageView mimage;
        String yonhu;

        public AuthorViewHolder(View itemView) {//学校界面初始化获取
            super(itemView);
            mContent = (LinearLayout) itemView.findViewById(R.id.school_content);
            mNickNameView = (TextView) itemView.findViewById(R.id.tv_schoolname);
            mRate = (TextView) itemView.findViewById(R.id.rate);
            mbtnTop = (Button) itemView.findViewById(R.id.btnTop);
            mbtnDelete = (Button) itemView.findViewById(R.id.btnDelete);
            mbtnAdd = (Button) itemView.findViewById(R.id.btnAdd);
            mimage = (ImageView) itemView.findViewById(R.id.iv_portrait);
            School = (TextView) itemView.findViewById(R.id.school);
            low = (TextView) itemView.findViewById(R.id.low);

        }
    }
}
